﻿// ***********************************************************************
// Assembly         : OSS
// Author           : tian_
// Created          : 11-20-2019
//
// Last Modified By : tian_
// Last Modified On : 11-28-2019
// ***********************************************************************
// <copyright file="OssApp.cs" company="">
//     Copyright ©  2019
// </copyright>
// <summary></summary>
// ***********************************************************************

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using Dos.ORM;
using Newtonsoft.Json;
using Osg;
using OSS.BIM.Commands.GroupCmds;
using OSS.BIM.Commands.GroupModelCmds;
using OSS.BIM.Commands.ProjcetCmds;
using OSS.BIM.Model;
using OSS.BIM.SceneManage;
using OSS.BIM.UI.Controls;
using OSS.BIM.Utility;
using OSS.Cmds;
using OSS.Doc.Cmds;
using OSS.Doc.Cmds.TestCmds;
using OSS.Earth.Commands;
using OSS.ModelViewer.Commands.TestCmds;
using OSS.Properties;
using Zf3DPlatform.osgEarth.Commands.AnimationCmds;
using Zf3DPlatform.osgEarth.Commands.MeasuringToolsCmds;
using Zf3DPlatform.osgEarth.Commands.ViewCmds;
using ZFGK.Addins;
using ZFGK.DataExchange;
using ZFGK.DevExprss.Utility;
using ZFGK.DocFrame.Objects;
using ZFGK.DocFrame.Utility;
using ZFGK.IO;
using ZFGK.OSG.DevExpressGUI;
using ZFGK.OSG.DocUI.Commands;
using ZFGK.OSG.UI;
using ZFGK.OSG.UI.Commands;
using ZFGK.OSG.Utility;
using ZFGK.osgEarth.PlatformGUI.Commands.ImageLayerCmds;
using ZFGK.osgEarth.PlatformGUI.Commands.ViewCmds;
using ZFGK.osgEarth.PlatformGUI.osgEarth.Commands.ToolCmds;
using ZFGK.osgEarth.PlatformGUI.Utility;
using ZFGK.osgEarth.UI;
using ZFGK.osgEarth.UI.Commands.DigitalEarthCmds;
using ZFGK.OsgOcc.Doc.CustomEntity;
using ZFGK.SQLite;
using ZFGK.Utility;
using ZFGK.WinForms.Utility;
using ZfPlatform.DevExpressGUI;
using ZfWebEarth;
using Timer = System.Windows.Forms.Timer;

namespace OSS
{
    /// <summary>
    /// Class OssApp.
    /// </summary>
    /// <seealso cref="ZFGK.Addins.IExtendApp" />
    public class OssApp : IExtendApp
    {
        /// <summary>
        /// The main ribbon form
        /// </summary>
        public static MainRibbonForm mainRibbonForm;

        /// <summary>
        /// Gets the active earth view form.
        /// </summary>
        /// <value>The active earth view form.</value>
        public static OsgEarthViewForm ActiveEarthViewForm
        {
            get { return mainRibbonForm.ActiveMdiChild as OsgEarthViewForm; }
        }
        public static OsgViewForm ActiveViewForm
        {
            get { return mainRibbonForm.ActiveMdiChild as OsgViewForm; }
        }

        public static readonly ZfOsgObjTreeList ZfOsgObjTreeList = new ZfOsgObjTreeList();

        static OssApp()
        {
            ZfDocument.CustomEntityTypes.Add(typeof(ZfOsgOccEntity));
        }
        /// <summary>
        /// Starts up.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool StartUp(ExtendAppData data)
        {
            Zf3DViewpointUIUtil.BindUI();
            if (!BmDatabaseUtil.CheckAndUpdate()) return false;

            mainRibbonForm = data.MainForm as MainRibbonForm;
            mainRibbonForm.Text = "开放场景工作室-开源";
            mainRibbonForm.Icon = Resources.OpenSceneStudio_Ico;
            mainRibbonForm.siAbout.Caption = "北京智帆高科科技有限公司 QQ群:469468407";

            InitDocCmdAndRibbonMenu(mainRibbonForm);
            InitModelViewerCmdAndRibbonMenu(mainRibbonForm);
            InitEarthCmdAndRibbonMenu(mainRibbonForm);
            InitBimCmdAndRibbonMenu(mainRibbonForm);
            InitToolCmdAndRibbonMenu(mainRibbonForm);

            var addinService = AddinManager.AddinService;
            addinService.RegisterCmd<AddStateSetManipulatorCmd>("AddStateSetManipulator");
            addinService.RegisterCmd<AddStatsHandlerCmd>("AddStatsHandler");

            var ribbonControl = mainRibbonForm.ribbonControl;
            ribbonControl.Pages.Move(0, ribbonControl.Pages.Count - 1);

            #region 添加浮动窗体

            ZfOsgObjTreeList.Dock = DockStyle.Fill;
            ZfOsgObjTreeList.PopupMenu = mainRibbonForm.popupMenu;
            var dockPanel10 = DockPanelUtil.New(ZfOsgObjTreeList,
                "模型树", new Guid("AE3DCB30-E539-44B6-8913-E14D5D6BEB60"), null);

            // 添加停靠窗体
            BmTreeListManager.treeList.PopupMenu = mainRibbonForm.popupMenu;
            BmTreeListManager.treeList.Dock = DockStyle.Fill;
            var dockPanel11 = DockPanelUtil.New(BmTreeListManager.treeList,
                "项目", new Guid("70a62a0b-1c55-4e72-bef0-661a97c3e934"), null);

            var dockPanel1 = DockPanelUtil.New(new[] {dockPanel10, dockPanel11}, "Project",
                new Guid("2035414A-3311-496B-AFE3-994CA45A98AC"));
            dockPanel1.Dock = DockingStyle.Left;

            PropertiesGridControl.Instance.PopupMenu = mainRibbonForm.popupMenu;
            PropertiesGridControl.Instance.Dock = DockStyle.Fill;
            var dockPanel2 = DockPanelUtil.New(PropertiesGridControl.Instance,
                "属性", new Guid("ED37992D-6DC2-4BD8-8A5C-BBD2C40522A7"), null);
            dockPanel2.Dock = DockingStyle.Right;

//             //BmPropertyGridCtrlUtil.Instance.PopupMenu = mainRibbonForm.popupMenu;
//             BmPropertyGridCtrlUtil.PropertyGridCtrl.Dock = DockStyle.Fill;
//             var dockPanel2 = DockPanelUtil.New(BmPropertyGridCtrlUtil.PropertyGridCtrl,
//                 "属性", new Guid("ED37992D-6DC2-4BD8-8A5C-BBD2C40522A7"), null);
//             dockPanel2.Dock = DockingStyle.Right;

            mainRibbonForm.dockManager.RootPanels.AddRange(new[] {  dockPanel1, dockPanel2 });
            mainRibbonForm.Controls.AddRange(new[] { dockPanel1, dockPanel2 });
            #endregion

            BmTreeListManager.InitTreeViewModel();
            BmTreeListManager.TreeList.AfterCheckNode += BmTreeListManager.BmTreeListOnAfterCheckNode;
            BmTreeListManager.TreeList.NodeCellStyle += BmTreeListManager.BmTreeListOnNodeCellStyle;
            BmTreeListManager.treeList.PreShowPopup += BmTreeListOnPreShowPopup;
            BmTreeListManager.TreeList.AfterFocusNode += BmTreeListOnAfterFocusNode;

            ZfOsgObjTreeList.PreShowPopup += ZfOsgObjTreeListOnPreShowPopup;

            mainRibbonForm.MdiChildActivate += MainRibbonFormOnMdiChildActivate;
            return true;
        }

        public static void InitToolCmdAndRibbonMenu(MainRibbonForm mainRibbonForm)
        {
            var ribbonControl = mainRibbonForm.ribbonControl;

            var addinService = AddinManager.AddinService;

            var toolPage = ribbonControl.Page("工具");

            addinService.RegisterCmd<OsgFileConvertCmd>();
            addinService.RegisterCmd<BoundBoxInfoCmd>();
            addinService.RegisterCmd<ModelCacheClearCmd>();
            addinService.RegisterCmd<ExchangeFilesToOneCmd>();
            addinService.RegisterCmd<OsgFileOptimizerCmd>();
            addinService.RegisterCmd<MoveToBottomCenterCmd>();
            addinService.RegisterCmd<ScaleModelCmd>();
            toolPage.Group("工具").ItemLinks
                .NewButton("文件转换", btn => btn.Tag = "OsgFileConvert", btn => btn.SetImage(Resources.loop_alt4_24, true))
                .NewButton("文件优化", btn => btn.Tag = "OsgFileOptimizer", btn => btn.SetImage(Resources.loop_alt4_24, true))
                .NewButton("模型大小", btn => btn.Tag = "BoundBoxInfo", btn => btn.SetImage(Resources.sizes, true));
        }

        #region 菜单
        /// <summary>
        /// Initializes the main form ribbon menu.
        /// </summary>
        /// <param name="mainRibbonForm">The main ribbon form.</param>
        public static void InitModelViewerCmdAndRibbonMenu(MainRibbonForm mainRibbonForm)
        {
            var ribbonControl = mainRibbonForm.ribbonControl;

            var addinService = AddinManager.AddinService;

            addinService.RegisterCmd<OpenOsgViewFormCmd>();

            var backstageViewControl = mainRibbonForm.backstageViewControl;
            backstageViewControl.Items
                .NewButtonItem("新建模型窗体", 0, btn => btn.Tag = "OpenOsgViewForm", btn => btn.SetImage(Resources._new));

            addinService.RegisterCmd<HighlightCancelCmd>();
            // 快捷按钮
            ribbonControl.Toolbar.ItemLinks
                .NewButton("取消高亮", btn => btn.Tag = ("HighlightCancel"), btn => btn.SetImage(Resources.cancel, false)
                    , btn => btn.Hint = ("取消所有模型的高亮"));

            var modelPage = ribbonControl.Page("模型");

            addinService.RegisterCmd<SetViewModeCmd>();
            modelPage.Group("视图").ItemLinks
                .NewButton("显示全图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.ShowAll), btn => btn.SetImage(Resources.cube, true))
                .NewButton("前视图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.Front), btn => btn.SetImage(Resources.front_side, false))
                .NewButton("后视图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.Back), btn => btn.SetImage(Resources.back_side, false))
                .NewButton("左视图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.Left), btn => btn.SetImage(Resources.left_side, false))
                .NewButton("右视图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.Right), btn => btn.SetImage(Resources.right_side, false))
                .NewButton("顶视图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.Top), btn => btn.SetImage(Resources.top_side, false))
                .NewButton("底视图", btn => btn.Tag = new CmdInfo("SetViewMode", ViewMode.Bottom), btn => btn.SetImage(Resources.bottom_side, false));

            addinService.RegisterCmd<OsgFileImportCmd>();
            addinService.RegisterCmd<OsgFileImportGroupCmd>();
            addinService.RegisterCmd<ModelDeleteCmd>();
            addinService.RegisterCmd<HighlightModelCmd>();
            addinService.RegisterCmd<ModelSaveAs>();
            addinService.RegisterCmd<BoundBoxDrawCmd>();
            addinService.RegisterCmd<NodeTreeToXmlFileCmd>(); ;
            addinService.RegisterCmd<SceneSaveAsCmd>();
            addinService.RegisterCmd<SceneClearCmd>();
            addinService.RegisterCmd<ViewerLightLntensityCmd>();
            addinService.RegisterCmd<ModelEditLightCmd>();
            modelPage.Group("场景").ItemLinks
                .NewButton("导入", btn => btn.Tag = "OsgFileImport", btn => btn.SetImage(Resources.import, false))
                .NewButton("导入组", btn => btn.Tag = "OsgFileImportGroup", btn => btn.SetImage(Resources.import, false))
                .NewButton("导出", btn => btn.Tag = "ModelSaveAs", btn => btn.SetImage(Resources.save, false))
                .NewButton("删除", btn => btn.Tag = "ModelDelete", btn => btn.SetImage(Resources.primitives, false))
                .NewButton("场景清空", btn => btn.Tag = "SceneClear", btn => btn.SetImage(Resources.primitives, false))
                .NewButton("场景导出", btn => btn.Tag = "SceneSaveAs", btn => btn.SetImage(Resources.save, false))
                .NewButton("模型光照", btn => btn.Tag = "ModelEditLight", btn => btn.SetImage(Resources.primitives, false))
                .NewButton("高亮", btn => btn.Tag = "HighlightModel", btn => btn.SetImage(Resources.primitives, false))
                .NewButton("取消高亮", btn => btn.Tag = "HighlightCancel", btn => btn.SetImage(Resources.cancel, false)
                    , btn => btn.Hint = "取消所有模型的高亮")
                .NewButton("绘制包围框", btn => btn.Tag = "BoundBoxDraw", btn => btn.SetImage(Resources.primitives, false))
                .NewButton("输出模型树", btn => btn.Tag = "NodeTreeToXmlFile", btn => btn.SetImage(Resources.primitives, false))
                .NewButton("光照强度", btn => btn.Tag = "ViewerLightLntensity", btn => btn.SetImage(Resources.primitives, false));

            addinService.RegisterCmd<OsgExchangeFilesImportCmd>();
//             modelPage.Group("数据交换").ItemLinks
//                 .NewButton("导入智帆工具箱导出数据", btn => btn.Tag = "OsgExchangeFilesImport", btn => btn.SetImage(Resources.import, false));
 //               .NewButton("智帆工具箱导出数据转单文件", btn => btn.Tag = "ExchangeFilesToOne", btn => btn.SetImage(Resources.sizes, false));
            //.NewButton("清除模型缓存", btn => btn.Tag = ("ModelCacheClear"), btn => btn.SetImage(Resources.火箭, true));


//             addinService.RegisterCmd<OpenAppConfigPathCmd>("OpenAppConfigPath");
//             ribbonControl.Page("地球").Group("配置").ItemLinks
//                 .NewButton("打开配置路径", btn => btn.Tag = ("OpenAppConfigPath"), btn => btn.SetImage(Resources.config, true));

//             addinService.RegisterCmd<SlantedImageTestCmd>("SlantedImageTest");
//             addinService.RegisterCmd<ChangeManipulatorCmd>("ChangeManipulator");
//             addinService.RegisterCmd<AddStateSetManipulatorCmd>("AddStateSetManipulator");
//             addinService.RegisterCmd<AddStatsHandlerCmd>("AddStatsHandler");
//             addinService.RegisterCmd<TestLineCmd>();

            addinService.RegisterCmd<PickPointPrintCmd>();

            addinService.RegisterCmd<OsgTianTengTestCmd>();
            addinService.RegisterCmd<OssTianTengTestCmd>();
            addinService.RegisterCmd<TianTengTestCmd>("EarthTianTengTest");
        }

        /// <summary>
        /// Initializes the earth command and ribbon menu.
        /// </summary>
        /// <param name="mainRibbonForm">The main ribbon form.</param>
        public static void InitEarthCmdAndRibbonMenu(MainRibbonForm mainRibbonForm)
        {
            var ribbonControl = mainRibbonForm.ribbonControl;

            var addinService = AddinManager.AddinService;

            addinService.RegisterCmd<OpenEarthFileCmd>();
            addinService.RegisterCmd<OpenEarthFormWithWebDataCmd>();
            var backstageViewControl = mainRibbonForm.backstageViewControl;
            backstageViewControl.Items
                .NewButtonItem("新建Earth窗体", 1, btn => btn.Tag = "OpenEarthFormWithWebData", btn => btn.SetImage(Resources._new))
                .NewButtonItem("打开Earth文件", 2, btn => btn.Tag = "OpenEarthFile", btn => btn.SetImage(Resources.open));

            addinService.RegisterCmd<FlyToCmd>();
            addinService.RegisterCmd<WeiZhiHuiZhengCmd>();
            // 快捷按钮
            ribbonControl.Toolbar.ItemLinks
                .NewButton("飞往", btn => btn.Tag = ("FlyTo"), btn => btn.SetImage(Resources.paper_plane_icon, false)
                    , btn => btn.Hint = ("飞往记录的视点"))
                .NewButton("位置回正", btn => btn.Tag = ("WeiZhiHuiZheng"), btn => btn.SetImage(Resources.compass, false)
                    , btn => btn.Hint = ("以顶视图查看位置"));

            var group = ribbonControl.Page("地球").Group("显示");
            var popupMenu = new PopupMenu();
            popupMenu.Ribbon = ribbonControl;

            addinService.RegisterCmd<FlyToViewPointShowCmd>();
            addinService.RegisterCmd<ViewScreenshotCmd>();
            popupMenu.NewButton("视点记录", btn => btn.Tag = "FlyToViewPointShow", btn => btn.SetImage(Resources.paper_plane_icon, true));
            group.ItemLinks
                .NewButton("飞往", btn => btn.Tag = ("FlyTo"), btn => btn.SetImage(Resources.paper_plane_icon, true)
                    , btn => btn.ButtonStyle = (BarButtonStyle.DropDown), btn => btn.DropDownControl = (popupMenu));
            group.ItemLinks
                .NewButton("位置回正", false,
                    btn => btn.Tag = ("WeiZhiHuiZheng"), btn => btn.SetImage(Resources.compass, true)
                    , btn => btn.Hint = "以顶视图查看位置");

            addinService.RegisterCmd<AddImageLayerCmd>();
            addinService.RegisterCmd<AddElevationLayerCmd>();
            addinService.RegisterCmd<UpdateImageLayerCmd>();
            addinService.RegisterCmd<HideOrShowLuWangCmd>();
            ribbonControl.Page("地球").Group("图层").ItemLinks
                .NewLinkContainer("卫星影像", btn => btn.SetImage(Resources.satellite, true));
            var barButtonGroup = ribbonControl.Page("地球").Group("图层").ItemLinks.GetBarItem("卫星影像") as BarLinkContainerItem;
            barButtonGroup.ItemLinks
                .NewCheck(SatelliteImageType.GOOGLE_EARTH_TILE.ToString(), "GoogleEarth", false, btn => btn.Tag = (new CmdInfo("UpdateImageLayer", SatelliteImageType.GOOGLE_EARTH_TILE)),
                    btn => btn.Checked = (true))
                .NewCheck(SatelliteImageType.GOOGLE_ChinaSatelliteMap_TILE.ToString(), "GoogleMapChina(有偏)", false, btn => btn.Tag = (new CmdInfo("UpdateImageLayer", SatelliteImageType.GOOGLE_ChinaSatelliteMap_TILE)))
                .NewCheck(SatelliteImageType.BING_SatelliteMap_TILE.ToString(), "BingChina", false, btn => btn.Tag = (new CmdInfo("UpdateImageLayer", SatelliteImageType.BING_SatelliteMap_TILE)))
                .NewCheck(SatelliteImageType.TIANDITU_MAP_TILE.ToString(), "天地图", false, btn => btn.Tag = (new CmdInfo("UpdateImageLayer", SatelliteImageType.TIANDITU_MAP_TILE)));
            ribbonControl.Page("地球").Group("图层").ItemLinks
                .NewCheck("显示隐藏路网", btn => btn.Tag = "HideOrShowLuWang", btn => btn.SetImage(Resources.maps, true), btn => btn.Checked = false);

            addinService.RegisterCmd<WebDataCacheCmd>();
            ribbonControl.Page("地球").Group("图层").ItemLinks
                .NewButton("缓存数据", btn => btn.Tag = ("WebDataCache"), btn => btn.SetImage(Resources.Downloads));

            addinService.RegisterCmd<MeasuringDistanceCmd>();
            addinService.RegisterCmd<MeasuringAreaCmd>();
            ribbonControl.Page("地球").Group("测量").ItemLinks
                .NewButton("距离", btn => btn.Tag = "MeasuringDistance", btn => btn.SetImage(Resources.MeasuringDistance, true))
                .NewButton("面积", btn => btn.Tag = "MeasuringArea", btn => btn.SetImage(Resources.MeasuringArea, true));

            addinService.RegisterCmd<QueryLocationCmd>();
            ribbonControl.Page("地球").Group("查询").ItemLinks
                .NewButton("位置查询", btn => btn.Tag = ("QueryLocation"), btn => btn.SetImage(Resources.loaction, true));

            addinService.RegisterCmd<AnimationViewPointShowCmd>();
            addinService.RegisterCmd<AnimationRunCmd>();
            ribbonControl.Page("地球").Group("动画").ItemLinks
                .NewButton("视点管理", btn => btn.Tag = "AnimationViewPointShow", btn => btn.SetImage(Resources.footprint, false))
                .NewButton("运行动画", btn => btn.Tag = "AnimationRun", btn => btn.SetImage(Resources.animation, false))
                .NewButton("录制动画", btn => btn.Tag = "AnimationRun",
                    btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false));

            //             addinService.RegisterCmd<ImportCadLineCmd>("ImportCadLine");
            //             ribbonControl.Page("地球").Group("绘制").ItemLinks
            //                 .NewButton("导入CAD线条", btn => btn.Tag = ("ImportCadLine"), btn => btn.SetImage(Resources.autocad, true));

            addinService.RegisterCmd<AddFeatureMaskLayerCmd>();
            addinService.RegisterCmd<AddFlatteningLayerCmd>();
            addinService.RegisterCmd<AddFeatureSourceLayerCmd>();
        }

        /// <summary>
        /// Initializes the bim command and ribbon menu.
        /// </summary>
        /// <param name="mainRibbonForm">The main ribbon form.</param>
        public static void InitBimCmdAndRibbonMenu(MainRibbonForm mainRibbonForm)
        {
            var ribbonControl = mainRibbonForm.ribbonControl;

            var addinService = AddinManager.AddinService;

            addinService.RegisterCmd<ShowCurUserGroupTreeNodeCmd>("ShowCurUserGroupTreeNode");
            ribbonControl.Page("BIM").Group("当前信息").ItemLinks
                .NewStatic("当前项目", "当前项目", false)
                .NewStatic("当前分组", "当前分组", false)
                .NewButton("显示当前", btn => btn.Tag = "ShowCurUserGroupTreeNode", btn => btn.SetImage(Resources.分组, false));

            addinService.RegisterCmd<ProjectNewCmd>();
            addinService.RegisterCmd<ProjectEditCmd>();
            addinService.RegisterCmd<ProjectDeleteCmd>();
            addinService.RegisterCmd<SetUserProjectCmd>();
            addinService.RegisterCmd<ProjectImportCmd>();
            ribbonControl.Page("BIM").Group("项目").ItemLinks
                .NewButton("添加", btn => btn.Tag = "ProjectNew", btn => btn.SetImage(Resources.项目添加, false))
                .NewButton("编辑", btn => btn.Tag = "ProjectEdit", btn => btn.SetImage(Resources.项目编辑, false))
                .NewButton("删除", btn => btn.Tag = "ProjectDelete", btn => btn.SetImage(Resources.项目删除, false))
                .NewButton("导入", btn => btn.Tag = "ProjectImport", btn => btn.SetImage(Resources.import, true));

            addinService.RegisterCmd<GroupAddCmd>();
            addinService.RegisterCmd<GroupEditCmd>();
            addinService.RegisterCmd<GroupDeleteCmd>();
            addinService.RegisterCmd<SetUserGroupCmd>();
            ribbonControl.Page("BIM").Group("组").ItemLinks
                .NewButton("添加", btn => btn.Tag = "GroupAdd", btn => btn.SetImage(Resources.分组添加, false))
                .NewButton("编辑", btn => btn.Tag = "GroupEdit", btn => btn.SetImage(Resources.分组编辑, false))
                .NewButton("删除", btn => btn.Tag = "GroupDelete", btn => btn.SetImage(Resources.分组删除, false));

            addinService.RegisterCmd<GroupModeAddCmd>();
            addinService.RegisterCmd<GroupModelMoveCmd>();
            addinService.RegisterCmd<GroupModelRotateCmd>();
            addinService.RegisterCmd<GroupModelEditCmd>();
            addinService.RegisterCmd<GroupModelDeleteCmd>();
            addinService.RegisterCmd<GroupModelShowCmd>();
            addinService.RegisterCmd<GroupModelLocationCmd>();
            ribbonControl.Page("BIM").Group("点模型").ItemLinks
                .NewButton("添加", btn => btn.Tag = "GroupModeAdd", btn => btn.SetImage(Resources.模型添加, false))
                .NewButton("导入", btn => btn.Tag = "GroupModeImport", btn => btn.SetImage(Resources.import, false))
                .NewButton("移动", btn => btn.Tag = "GroupModelMove", btn => btn.SetImage(Resources.模型移动, false))
                .NewButton("旋转", btn => btn.Tag = "GroupModelRotate", btn => btn.SetImage(Resources.模型旋转, false))
                .NewButton("编辑", btn => btn.Tag = "GroupModelEdit", btn => btn.SetImage(Resources.模型编辑, false))
                .NewButton("删除", btn => btn.Tag = "GroupModelDelete", btn => btn.SetImage(Resources.模型删除, false));

//             addinService.RegisterCmd<GroupLineModeAddlCmd>();
//             ribbonControl.Page("BIM").Group("线模型").ItemLinks
//                 .NewButton("添加", btn => btn.Tag = "GroupLineModeAdd", btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false))
//                 .NewButton("编辑", btn => btn.Tag = "GroupLineModeAdd", btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false))
//                 .NewButton("删除", btn => btn.Tag = "GroupLineModeAdd", btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false));
            
            ribbonControl.Page("BIM").Group("面模型").ItemLinks
                .NewButton("添加", btn => btn.Tag = "GroupLineModeAdd", btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false))
                .NewButton("编辑", btn => btn.Tag = "GroupLineModeAdd", btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false))
                .NewButton("删除", btn => btn.Tag = "GroupLineModeAdd", btn => btn.SetImage(Resources.wait_red, false), btn => btn.Enabled = (false));

            addinService.RegisterCmd<ProjectUpdateBorderPointsCmd>();
            addinService.RegisterCmd<ProjectSiteFormationCmd>();
        }

        public static void InitDocCmdAndRibbonMenu(MainRibbonForm mainRibbonForm)
        {
            var ribbonControl = mainRibbonForm.ribbonControl;
            var addinService = AddinManager.AddinService;

            addinService.RegisterCmd<NewDocCmd>("New");
            addinService.RegisterCmd<OpenDocCmd>("Open");
            addinService.RegisterCmd<SaveDocCmd>("Save");
            addinService.RegisterCmd<SaveAsDocCmd>("SaveAs");
            addinService.RegisterCmd<SaveDocSettingCmd>("SaveDocSetting");

            var backstageViewControl = mainRibbonForm.backstageViewControl;
            backstageViewControl.Items
                .NewButtonItem("新建", 0, btn => btn.Tag = "New", btn => btn.SetImage(Resources._new))
                .NewButtonItem("打开", 1, btn => btn.Tag = "Open", btn => btn.SetImage(Resources.open))
                .NewButtonItem("保存", 2, btn => btn.Tag = "Save", btn => btn.SetImage(Resources.save))
                .NewButtonItem("另存为", 3, btn => btn.Tag = "SaveAs", btn => btn.SetImage(Resources.save));

            addinService.RegisterCmd<RedoCmd>("Redo");
            addinService.RegisterCmd<UndoCmd>("Undo");
            addinService.RegisterCmd<RegenCmd>("Regen");
            addinService.RegisterCmd<DeleteEntityCmd>("Delete");
            addinService.RegisterCmd<MoveEntityCmd>("Move");
            ribbonControl.Page("编辑").Group("编辑").ItemLinks
                .NewButton("撤销", btn => btn.Tag = "Undo", btn => btn.SetImage(Resources.undo, false))
                .NewButton("重做", btn => btn.Tag = "Redo", btn => btn.SetImage(Resources.redo, false))
                .NewButton("重生成", btn => btn.Tag = "Regen", btn => btn.SetImage(Resources.refresh, false))
                .NewButton("删除实体", btn => btn.Tag = "Delete", btn => btn.SetImage(Resources.delete, false))
                .NewButton("移动", btn => btn.Tag = "Move", btn => btn.SetImage(Resources.move_64px, false));

            addinService.RegisterCmd<NewCubeCmd>();
            addinService.RegisterCmd<NewSphereCmd>();
            ribbonControl.Page("编辑").Group("造型").ItemLinks
                .NewButton("立方体", btn => btn.Tag = "NewCube", btn => btn.SetImage(Resources.undo, false))
                .NewButton("球体", btn => btn.Tag = "NewSphere", btn => btn.SetImage(Resources.undo, false));

            addinService.RegisterCmd<CutCmd>();
            addinService.RegisterCmd<FuseCmd>();
            addinService.RegisterCmd<SectionCmd>();
            addinService.RegisterCmd<CommonCmd>();
            ribbonControl.Page("编辑").Group("布尔运算").ItemLinks
                .NewButton("并", btn => btn.Tag = "Fuse", btn => btn.SetImage(Resources.undo, false))
                .NewButton("差", btn => btn.Tag = "Cut", btn => btn.SetImage(Resources.undo, false))
                .NewButton("交", btn => btn.Tag = "Common", btn => btn.SetImage(Resources.undo, false));

            addinService.RegisterCmd<NewSphereCmd>();

            addinService.RegisterCmd<ReadOccToDocCmd>();
            ribbonControl.Page("编辑").Group("测试").ItemLinks
                .NewButton("导入", btn => btn.Tag = "ReadOccToDoc", btn => btn.SetImage(Resources.undo, false));

            addinService.RegisterCmd<OccTestCmd>();
        }

        /// <summary>
        /// Called when [show tree list popup menu].
        /// </summary>
        /// <param name="treeListPopupMenu">The tree list popup menu.</param>
        /// <param name="treeNode">The tree node.</param>
        public static void BmTreeListOnPreShowPopup(PopupMenu treeListPopupMenu, TreeListNode treeNode)
        {
            if (treeNode == null)
                return;
            if (treeNode.Tag == null && treeNode.GetValue(0).ToString() == "项目")
            {
                treeListPopupMenu
                    .NewButton("添加", btn => btn.Tag = new CmdInfo("ProjectNew", treeNode.Tag), btn => btn.SetImage(Resources.project, false));
            }
            if (treeNode.Tag is Project)
            {
                // 使用数据库中最新的数据
                var project = treeNode.Tag as Project;

                treeListPopupMenu
                    .NewButton("编辑", btn => btn.Tag = new CmdInfo("ProjectEdit", project), btn => btn.SetImage(Resources.project, false))
                    .NewButton("定位", btn => btn.Tag = new CmdInfo("ProjectLocation", project), btn => btn.SetImage(Resources.project, false))
                    .NewButton("更新边界", btn => btn.Tag = new CmdInfo("ProjectUpdateBorderPoints", project), btn => btn.SetImage(Resources.project, false))
                    .NewButton("场地平整", btn => btn.Tag = new CmdInfo("ProjectSiteFormation", project), btn => btn.SetImage(Resources.project, false))
                    .NewButton("导入", true, btn => btn.Tag = new CmdInfo("ProjectImport", project), btn => btn.SetImage(Resources.project, false));
            }
        }
        #endregion

        /// <summary>
        /// Trees the list on after focus node.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="NodeEventArgs"/> instance containing the event data.</param>
        private void BmTreeListOnAfterFocusNode(object sender, NodeEventArgs e)
        {
            var activeEarthViewForm = ActiveEarthViewForm;
            if (activeEarthViewForm == null)
                return;
            var osgEarthObj = activeEarthViewForm.OsgEarthViewCtrl.OsgEarthObj;
            var modelElement = e.Node.Tag as ModelElement;
            if (modelElement != null)
            {
                osgEarthObj.FxClear();
                osgEarthObj.OutlineNode(modelElement.GetGroupName(), modelElement.ModelElementId.ToString(), new Vec4f(1, 0, 0, 1));
            }
            PropertiesGridControl.Instance.ModelElement = modelElement;
        }


        private void MainRibbonFormOnMdiChildActivate(object sender, EventArgs e)
        {
            foreach (var form in mainRibbonForm.MdiChildren)
            {
                if (form is OsgViewForm)
                {
                    var osgViewForm = form as OsgViewForm;
                    osgViewForm.OsgViewCtrl.OsgMouseClick -= OsgViewOnMouseClick;
                    osgViewForm.OsgViewCtrl.MouseMove -= OsgViewCtrlOnMouseMove;
                    osgViewForm.OsgViewCtrl.MouseWheel -= OsgViewCtrlOnMouseWheel;
                }
            }

            if (mainRibbonForm.ActiveMdiChild is OsgViewForm)
            {
                var osgViewForm = mainRibbonForm.ActiveMdiChild as OsgViewForm;
                osgViewForm.OsgViewCtrl.OsgMouseClick += OsgViewOnMouseClick;
                osgViewForm.OsgViewCtrl.MouseMove += OsgViewCtrlOnMouseMove;
                osgViewForm.OsgViewCtrl.MouseWheel += OsgViewCtrlOnMouseWheel;
            }

            bool bCanShowOsgNodeTree = false;
            if (mainRibbonForm.ActiveMdiChild is IViewForm)
            {
                var viewForm = mainRibbonForm.ActiveMdiChild as IViewForm;
                if (viewForm.View is IOsgViewCtrl)
                {
                    var osgViewCtrl = viewForm.View as IOsgViewCtrl;

                    ZfOsgObjTreeList.Set(osgViewCtrl.OsgObj);

                    bCanShowOsgNodeTree = true;
                }
            }
            if (!bCanShowOsgNodeTree)
            {
                ZfOsgObjTreeList.Set(null);
            }
        }

        private void OsgViewOnMouseClick(object sender, MouseEventArgs e)
        {
            if (AddinManager.AddinService.IsCmdRun)
                return;

            var osgViewForm = ActiveViewForm;
            if (osgViewForm.OsgViewCtrl.ActionOperator.Actions.Count > 1)
                return;

            if (timer.Enabled)
                return;

            var osgViewCtrl = osgViewForm.OsgViewCtrl;

            // 注意，osg的视图坐标系在右下角
            int x = e.X;
            int y = osgViewCtrl.Height - e.Y;
            if (e.Button == MouseButtons.Left)
            {
                PropertiesGridControl.Instance.SetProperties(null);
                osgViewCtrl.OsgObj.OutlineClear();

                osgViewCtrl.OsgObj.GUIEventHandler.DoOnce(() =>
                {
                    var groups = osgViewCtrl.OsgObj.GroupFolder.GetChildren().ToArray();

                    Group selectGroup;
                    Node selectNode, childeNode;
                    Vec3d worldPt;
                    var camera = osgViewCtrl.OsgObj.Viewer.getCamera();
                    if (OsgIntersectorUtil.Intersect(camera, x, y, groups, out selectGroup, out selectNode,
                        out childeNode, out worldPt))
                    {
                        osgViewCtrl.SafeInvoke(() =>
                        {
                            var items = selectNode.Name.Split(' ');
                            if (items == null || items.Length < 2)
                                return;
                            var elementId = ConvertUtil.ToInt64(items[1], 0);
                            if (elementId == 0)
                                return;
                            var groupFilePath = selectGroup.Name;
                            if (!File.Exists(groupFilePath))
                                return;
                            var dbFilePath = groupFilePath.ChangeExtension(".db");
                            if (!File.Exists(dbFilePath))
                                return;

                            var properties = new List<ModelProperty>();
                            // 插入属性
                            var dbSession = new DbSession(DatabaseType.Sqlite3, ZfSQLiteUtil.GetConStr(dbFilePath));
                            var elementPropertyDb = dbSession.From<OSS.Models.ElementProperty>().Where(d => d.ElementId == elementId).First();
                            if (elementPropertyDb != null)
                            {
                                var elementProperty =
                                    JsonConvert.DeserializeObject<ElementProperty>(elementPropertyDb.Property);
                                if (elementProperty != null)
                                {
                                    foreach (var property in elementProperty.Properties)
                                    {
                                        var modelProperty = new ModelProperty();
                                        modelProperty.Name = property.Name;
                                        modelProperty.DiaplayLable = property.DisplayLable;
                                        modelProperty.Value = property.Value;
                                        properties.Add(modelProperty);
                                    }

                                    foreach (var category in elementProperty.Categories)
                                    {
                                        foreach (var property in category.Properties)
                                        {
                                            var modelProperty = new ModelProperty();
                                            modelProperty.Name = property.Name;
                                            modelProperty.DiaplayLable = property.DisplayLable;
                                            modelProperty.Value = property.Value;
                                            properties.Add(modelProperty);
                                        }
                                    }
                                }
                            }

                            PropertiesGridControl.Instance.SetProperties(properties.Where(d => !d.Value.IsNullOrEmpty()).ToList());
                            osgViewCtrl.OsgObj.OutlineNode(new[] { selectNode });
                        });
                    }
                });
            }
            if (e.Button == MouseButtons.Right)
            {
                osgViewCtrl.OsgObj.GUIEventHandler.DoOnce(() =>
                {
                    var camera = osgViewCtrl.OsgObj.Viewer.getCamera();
                    var intersections = OsgIntersectorUtil.PolytopeIntersect(camera, x, y).getIntersections();
                    if (intersections.Count > 0)
                    {
                        osgViewCtrl.SafeInvoke(() =>
                        {
//                             mainRibbonForm.popupMenu.ItemLinks.Clear();
//                             mainRibbonForm.popupMenu.NewButton("添加地物", false,
//                                 btn => btn.Tag = (new CmdInfo(typeof(FeatureAddCmd), mapPt)));
//                             mainRibbonForm.popupMenu.ShowPopup(Control.MousePosition);
                        });
                    }
                });
            }
        }

        private Timer timer = new Timer();
        private void OsgViewCtrlOnMouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right || e.Button == MouseButtons.Middle)
            {
                ModelHide();
            }
        }

        private void OsgViewCtrlOnMouseWheel(object sender, MouseEventArgs e)
        {
            ModelHide();
        }

        private void TimerOnTick(object sender, EventArgs e)
        {
            ModelShow();
        }

        private void ModelHide()
        {
            if (timer.Enabled) // 如果正在运行，重新计时
            {
                timer.Stop();
                timer.Start();
                return;
            }
            timer.Interval = 500;
            timer.Tick -= TimerOnTick;
            timer.Tick += TimerOnTick;

            var osgViewCtrl = ActiveViewForm.OsgViewCtrl;
            osgViewCtrl.OsgObj.GUIEventHandler.DoOnce(delegate ()
            {
                osgViewCtrl.OsgObj.GroupFolder.GetChildren().ForEach(
                    delegate (Node node, int index)
                    {
                        if (index > 0 && node.IsValid() && node.NodeMask != 0)
                        {
                            node.NodeMask = 0;
                        }
                    });
                osgViewCtrl.SafeInvoke(delegate () { timer.Start(); });
            });
        }

        private void ModelShow()
        {
            timer.Stop();
            var osgViewCtrl = ActiveViewForm.OsgViewCtrl;
            osgViewCtrl.OsgObj.GUIEventHandler.DoOnce(delegate ()
            {
                osgViewCtrl.OsgObj.GroupFolder.GetChildren().ForEach(
                    delegate (Node node, int index)
                    {
                        if (index > 0 && node.IsValid() && node.NodeMask != 1)
                        {
                            node.NodeMask =1;
                        }
                    });
            });
        }

        private static void NewMethod(Node selectNode, ZfOsgViewCtrl osgViewCtrl)
        {
            if (selectNode.getNumDescriptions() == 0)
                return;
            osgViewCtrl.SafeInvoke(() =>
            {
                PropertiesGridControl.Instance.SetProperties(null);
                osgViewCtrl.OsgObj.OutlineClear();
                var xmlFilePath = selectNode.getDescription(0);

                var properties = new List<ModelProperty>();
                if (File.Exists(xmlFilePath))
                {
                    try
                    {
                        var elementProperty =
                            XmlSerializerUtil.DeserializeFormF<ElementProperty>(xmlFilePath);
                        foreach (var property in elementProperty.Properties)
                        {
                            var modelProperty = new ModelProperty();
                            modelProperty.Name = property.Name;
                            modelProperty.DiaplayLable = property.DisplayLable;
                            modelProperty.Value = property.Value;
                            properties.Add(modelProperty);
                        }

                        foreach (var category in elementProperty.Categories)
                        {
                            foreach (var property in category.Properties)
                            {
                                var modelProperty = new ModelProperty();
                                modelProperty.Name = property.Name;
                                modelProperty.DiaplayLable = property.DisplayLable;
                                modelProperty.Value = property.Value;
                                properties.Add(modelProperty);
                            }
                        }

                        PropertiesGridControl.Instance.SetProperties(properties);
                        osgViewCtrl.OsgObj.OutlineNode(new[] {selectNode});
                    }
                    catch
                    {
                    }
                }
            });
        }

        private void ZfOsgObjTreeListOnPreShowPopup(PopupMenu menu, TreeListNode arg2)
        {
            if (arg2 == null)
                return;

        }
    }
}
